package com.ruoyi.common.utils;

import com.ruoyi.common.core.domain.FrontTreeObj;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TreeUtils {

    public static List<FrontTreeObj> buildTreeSelect(List<FrontTreeObj> frontTreeObjList){
        return buildTree(frontTreeObjList);
    }


    public static List<FrontTreeObj> buildTree(List<FrontTreeObj> frontTrees)
    {
        List<FrontTreeObj> returnList = new ArrayList<FrontTreeObj>();
        List<Long> tempList = new ArrayList<Long>();
        for (FrontTreeObj fto : frontTrees)
        {
            tempList.add(fto.getId());
        }
        for (Iterator<FrontTreeObj> iterator = frontTrees.iterator(); iterator.hasNext();)
        {
            FrontTreeObj fto = (FrontTreeObj) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(fto.getParentId()))
            {
                recursionFn(frontTrees, fto);
                returnList.add(fto);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = frontTrees;
        }
        return returnList;
    }

    private static void recursionFn(List<FrontTreeObj> list, FrontTreeObj t)
    {
        // 得到子节点列表
        List<FrontTreeObj> childList = getChildList(list, t);
        t.setChildren(childList);
        for (FrontTreeObj tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    private static List<FrontTreeObj> getChildList(List<FrontTreeObj> list, FrontTreeObj t)
    {
        List<FrontTreeObj> tlist = new ArrayList<FrontTreeObj>();
        Iterator<FrontTreeObj> it = list.iterator();
        while (it.hasNext())
        {
            FrontTreeObj n = (FrontTreeObj) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    private static boolean hasChild(List<FrontTreeObj> list, FrontTreeObj t)
    {
        return getChildList(list, t).size() > 0;
    }
}
